package self.zhangkang.android.network

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Build
import android.widget.Toast

/**
 * Created on 2019/10/9
 * Title: 网络变化监听器
 * Description:
 *
 * @author Android-张康
 */
class NetworkChangeReceiver : BroadcastReceiver() {
//    private val mNetworkChangeReceiver = NetworkChangeReceiver()
//    init {
//        val intentFilter = IntentFilter()
//        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
//        registerReceiver(mNetworkChangeReceiver, intentFilter)
//    }

    override fun onReceive(context: Context?, intent: Intent?) {
        context ?: return
        val connectivity =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            val activeNetworkInfo = connectivity.activeNetworkInfo
            if (activeNetworkInfo?.isAvailable == true) {
                when (activeNetworkInfo.type) {
                    ConnectivityManager.TYPE_MOBILE -> {
                        Toast.makeText(context, "当前使用4G", Toast.LENGTH_SHORT).show()
                    }
                    ConnectivityManager.TYPE_WIFI -> {
                        Toast.makeText(context, "当前使用WIFI", Toast.LENGTH_SHORT).show()
                    }
                    else -> {
                        Toast.makeText(context, "当前网络可用", Toast.LENGTH_SHORT).show()
                    }
                }
            } else {
                Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show()
            }
        } else {
            val allNetworks = connectivity.allNetworks
            for (allNetwork in allNetworks) {
                val networkInfo = connectivity.getNetworkInfo(allNetwork)
                networkInfo?.typeName
            }
        }

    }

}